import React                from 'react';

import ClickAwayListener    from './internal/ClickAwayListener';

import './Toast.scss';

export default class Toast extends React.Component {

    state = {visible: false};

    children = null;

    componentWillReceiveProps({open}){
        if(this.props.open !== open && open){
            this.show();
        }
    }

    componentWillUnmount(){
        clearTimeout(this.timer);
    }

    show(){
        if(!this.state.visible){
            this.setState({visible: true});
            this.timer = setTimeout(() => this.hide(), this.props.duration);
        }
    }

    abort(){
        clearTimeout(this.timer);
        this.hide();
    }

    hide(){
        if(this.state.visible){
            this.setState({visible: false});
            this.props.onRequestClose();
        }
    }

    render(){
        var {className = '', children} = this.props;
        var {visible} = this.state;
        return (
            <ClickAwayListener onClickAway={visible ? () => this.abort() : null}>
                <div className={`snack ${visible ? 'show' : 'hide'}`}>
                    <div className={`s-content flex-avg ${className}`}>
                        {this.children = visible ? children : this.children}
                    </div>
                </div>
            </ClickAwayListener>
        );
    }

}

Toast.defaultProps = {
    open: false,
    duration: 3000,
    onRequestClose: () => null,
};
